var files = [];
var oldfiles = [];
var filename = [];
layui.define(['table', 'form', 'laypage', 'laydate', 'layer', 'carousel'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , laydate = layui.laydate
        , laypage = layui.laypage
        , layer = layui.layer
        , carousel = layui.carousel;

    //路径
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);

    var cols = [{title: 'ID', width: 70, sort: true, fixed: 'left', type: 'numbers'},
        {field: 'filename', title: '文件名', sort: true},
        {field: 'filetype', title: '文件类型', sort: true},
        {field: 'filesize', title: '文件大小', sort: true},
        {field: 'uploadtime', title: '上传时间', sort: true},
        {field: 'uploaduser', title: '操作人', sort: true},
        {title: '操作', toolbar: '#table-files', align: "center", width: 200, fixed: "right"}]
    var limitcount = 10;
    var tid = $("#filetid").val();
    var type = $("#filetype").val();
    var size = 0;
    var olddata = [];
    var initflag = true;
    table.render({
        elem: '#files'
        , url: localhostPath + projectName + "/rest/base/getFilesListByTid"
        // , data:[]
        , title: "文件列表"
        , height: 'full-220'
        , page: false
        , limit: limitcount
        , text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        },
        toolbar: '#filesOperation',
        defaultToolbar: ['filter']
        // ,skin: 'line' //表格风格
        , cols: [cols],
        where: {tid: tid,type:type},
        done: function (res, curr, count) {
            var data = res.data;
            if(initflag){
                for (var p in data){
                    olddata.push(data[p]);
                }
                initflag = false;
            }
            $('.layui-table-fixed-r').removeClass('layui-hide');//列固定右侧
            var curnum = $("#curnum").val();
            laypage.render({
                elem: 'laypage'
                , first: '首页'
                , last: '尾页'
                , groups: 5
                , count: count
                , curr: curnum
                , limit: limitcount
                , layout: ['prev', 'page', 'next', 'skip', 'count', 'limit']
                , limits: [10, 15, 20]
                , jump: function (obj, first) {
                    if (!first) {
                        curnum = obj.curr;
                        $("#curnum").val(curnum)
                        limitcount = obj.limit;
                        table.reload('files', { //表格的id
                            where: {
                                page: curnum,
                                limit: limitcount
                            }
                        })
                    }
                }
            })
        }
    });
    //监听工具条
    table.on('tool(filesTables)', function (obj) {  //表格的lay-filter="userlists"
        var data = obj.data; //获得当前行所有数据
        if (obj.event === 'info') {
            info(data);
        } else if (obj.event === 'del') {
            del(data,obj);
        }
    });
    function del(data,obj){
        layer.confirm('确定删除此文件', {icon: 3, title: '提示信息', shade: 0.6}, function (index) {
            layer.close(index);
            layer.msg('删除中，请稍候', {icon: 16, time: false, shade: 0.6});
            setTimeout(function () {
                var flag = true;
                if(flag){
                    for (var i = 0; i < oldfiles.length; i++){
                        if(data.name == oldfiles[i].substring(oldfiles[i].lastIndexOf("/") + 10)){
                            oldfiles.splice(i,1);
                            filename.splice(i,1);
                            flag = false;
                        }
                    }
                }
                if(flag){
                    for (i = 0; i < files.length; i++){
                        if(data.name == files[i].name){
                            files.splice(i,1);
                            filename.splice(i + oldfiles.length,1);
                        }
                    }
                }
                for (i = 0; i < olddata.length; i++){
                    if(data.name == olddata[i].name){
                        olddata.splice(i,1);
                    }
                }
                layer.msg('删除成功');
                obj.del();
                document.getElementById("filetext").value = filename.toString();
            }, 2000);
        });
    }
    function info(data) {
        window.open(localhostPath + projectName +"/rest/base/downloadFile?filepath="+data.filepath);
    }
    function getSize(length) {
        if(length > 1024){
            length = length / 1024;
            if(length > 1024){
                length = length / 1024;
                if(length > 1024){
                    length = length / 1024;
                    return Math.ceil(length) + "GB";
                }else {
                    return Math.ceil(length) + "MB";
                }
            }else {
                return Math.ceil(length) + "KB";
            }
        }else {
            return Math.ceil(length) + "B";
        }
    }
    function inittable(files){//上传文件解析
        var data = [];
        Array.prototype.push.apply(data,olddata);
        for(var i = 0; i < files.length; i++){
            var file = files[i];
            var json = {
                "filename":file.name.substring(0,file.name.lastIndexOf(".")),
                "filetype":file.name.substring(file.name.lastIndexOf(".") + 1),
                "filesize":getSize(file.size),
                "uploadtime":$("#datetime").val(),
                "uploaduser":$("#username").val(),
                "filepath":file.name,
                "name":file.name,
            };
            data.push(json);
        }
        table.reload('files', { //表格的id
            data:data,
            url:null,
            // cols: [cols],
        });
        // $("#delindex").val("");
    }
    $(document).on('change',"#changefile",function () {
        var fileData = this.files;
        var pNode = this.parentNode.parentNode;
        if(fileData.length + oldfiles.length + files.length > 10){
            layer.msg("上传文件过多，最多只能上传10个文件", {icon: 5, anim: 6});
            this.value = null;
        }else if(fileData.length > 0){
            for(var i = 0; i < fileData.length; i++){
               size = size +  fileData[i].size;
            }
            if(size >= 10485760000){
                layer.msg("上传文件之和过大，请选择文件之和小于9G的文件", {icon: 5, anim: 6});
                this.value = null;
            }else {
                for(var j = 0; j < fileData.length; j++){
                    files.push(fileData[j]);
                    filename.push(fileData[j].name);
                }
                var filetext = document.getElementById("filetext");
                if(filetext != null){
                    filetext.value = filename.toString();
                }else {
                    $("<div class='layui-col-xs9'>\n" +
                        "<div class='layui-input-block' style='margin-left: -30px;' id='file'>\n" +
                        "<textarea class='layui-textarea' readonly='readonly' id='filetext'>" + filename.toString()+"</textarea>\n" +
                        "</div>\n" +
                        "</div>").insertAfter(pNode);
                }
                $("#fileupdate").val("1");
                inittable(files);
            }
        }
    });
    exports('files', {})
});
function initfiles(filepath) {
    oldfiles = filepath.split(",");//遍历原有的文件
    if(oldfiles.length > 0){
        for (var i = 0; i < oldfiles.length; i++){
            var file = oldfiles[i];
            filename.push(file.substring(file.lastIndexOf("/")+10));
        }
    }
    var pNode = document.getElementById("file");
    $("<div class='layui-col-xs9'>\n" +
        "<div class='layui-input-block' style='margin-left: -30px;' id='file'>\n" +
        "<textarea class='layui-textarea' readonly='readonly' id='filetext'>"+filename.toString()+"</textarea>\n" +
        "</div>\n" +
        "</div>").insertAfter(pNode);
}
function getFormData() {
    var formData = new FormData($("#form")[0]);
    formData.set("uploadFile","");
    formData.append("oldfiles",oldfiles.toString());
    for (i = 0; i < files.length; i++){
        formData.append("uploadFile",files[i]);
    }
    return formData;
}